#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Markdown到紧凑A4 Word文档转换器
减少空白，提高内容密度
"""

import re

def convert_markdown_to_compact_a4(md_file_path, output_path):
    """将Markdown文件转换为紧凑的A4标准HTML"""
    
    with open(md_file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 紧凑A4 HTML模板
    html_template = '''<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>类小脑计算平台技术规格书</title>
    <style>
        @page {{
            size: A4;
            margin: 1.5cm 2cm 1.5cm 2cm; /* 减小边距 */
        }}
        
        body {{
            font-family: "Microsoft YaHei", "Times New Roman", serif;
            font-size: 11pt; /* 稍小字体 */
            line-height: 1.3; /* 紧凑行距 */
            color: #000;
            margin: 0;
            padding: 0;
            background: white;
        }}
        
        h1 {{
            font-size: 16pt;
            font-weight: bold;
            text-align: center;
            margin: 8pt 0 12pt 0; /* 减小间距 */
            color: #000;
            page-break-after: avoid;
        }}
        
        h2 {{
            font-size: 14pt;
            font-weight: bold;
            margin: 10pt 0 6pt 0; /* 减小间距 */
            color: #000;
            page-break-after: avoid;
            border-bottom: 1pt solid #ccc;
            padding-bottom: 2pt;
        }}
        
        h3 {{
            font-size: 12pt;
            font-weight: bold;
            margin: 8pt 0 4pt 0; /* 减小间距 */
            color: #333;
            page-break-after: avoid;
        }}
        
        h4 {{
            font-size: 11pt;
            font-weight: bold;
            margin: 6pt 0 3pt 0; /* 减小间距 */
            color: #333;
            page-break-after: avoid;
        }}
        
        h5, h6 {{
            font-size: 11pt;
            font-weight: bold;
            margin: 4pt 0 2pt 0; /* 减小间距 */
            color: #333;
            page-break-after: avoid;
        }}
        
        p {{
            margin: 3pt 0; /* 大幅减小段落间距 */
            text-align: justify;
            text-indent: 0;
        }}
        
        ul, ol {{
            margin: 4pt 0; /* 减小列表间距 */
            padding-left: 18pt;
        }}
        
        li {{
            margin: 1pt 0; /* 减小列表项间距 */
            line-height: 1.3;
        }}
        
        table {{
            width: 100%;
            border-collapse: collapse;
            margin: 6pt 0; /* 减小表格间距 */
            font-size: 9pt; /* 表格用更小字体 */
        }}
        
        th, td {{
            border: 0.5pt solid #666;
            padding: 3pt; /* 减小单元格内边距 */
            text-align: left;
            vertical-align: top;
        }}
        
        th {{
            background-color: #f0f0f0;
            font-weight: bold;
            text-align: center;
            font-size: 9pt;
        }}
        
        pre {{
            font-family: "Consolas", "Courier New", monospace;
            font-size: 8pt; /* 代码用更小字体 */
            background-color: #f8f8f8;
            border: 0.5pt solid #ccc;
            padding: 4pt;
            margin: 4pt 0; /* 减小代码块间距 */
            white-space: pre-wrap;
            word-wrap: break-word;
            line-height: 1.2;
        }}
        
        code {{
            font-family: "Consolas", "Courier New", monospace;
            font-size: 9pt;
            background-color: #f0f0f0;
            padding: 1pt;
            border-radius: 2pt;
        }}
        
        hr {{
            border: none;
            border-top: 0.5pt solid #666;
            margin: 6pt 0; /* 减小分隔线间距 */
        }}
        
        .ascii-art {{
            font-family: "Consolas", "Courier New", monospace;
            font-size: 7pt; /* ASCII艺术用最小字体 */
            white-space: pre;
            background-color: #f8f8f8;
            border: 0.5pt solid #ccc;
            padding: 3pt;
            margin: 3pt 0;
            line-height: 1.1;
        }}
        
        .json-block {{
            font-family: "Consolas", "Courier New", monospace;
            font-size: 8pt;
            background-color: #f5f5f5;
            border-left: 3pt solid #007acc;
            padding: 4pt;
            margin: 4pt 0;
            white-space: pre-wrap;
        }}
        
        .http-block {{
            font-family: "Consolas", "Courier New", monospace;
            font-size: 8pt;
            background-color: #f0f8ff;
            border-left: 3pt solid #28a745;
            padding: 4pt;
            margin: 4pt 0;
            white-space: pre-wrap;
        }}
        
        /* 移除不必要的空白 */
        .no-margin {{
            margin: 0 !important;
        }}
        
        /* 打印优化 */
        @media print {{
            body {{
                font-size: 10pt;
                line-height: 1.2;
            }}
            h1 {{ font-size: 14pt; margin: 6pt 0 8pt 0; }}
            h2 {{ font-size: 12pt; margin: 6pt 0 4pt 0; }}
            h3 {{ font-size: 11pt; margin: 4pt 0 2pt 0; }}
            h4, h5, h6 {{ font-size: 10pt; margin: 3pt 0 1pt 0; }}
            p {{ margin: 2pt 0; }}
            table {{ font-size: 8pt; }}
            pre {{ font-size: 7pt; }}
            .ascii-art {{ font-size: 6pt; }}
        }}
    </style>
</head>
<body>
{content}
</body>
</html>'''
    
    # 转换Markdown内容
    html_content = convert_md_content_compact(content)
    
    # 生成完整HTML
    full_html = html_template.format(content=html_content)
    
    # 保存HTML文件
    with open(output_path, 'w', encoding='utf-8') as f:
        f.write(full_html)
    
    print(f"紧凑A4文档已生成: {output_path}")
    print("\n优化特性:")
    print("✓ 减小边距和间距")
    print("✓ 优化字体大小")
    print("✓ 紧凑行距")
    print("✓ 减少空白区域")
    print("✓ 提高内容密度")

def convert_md_content_compact(content):
    """转换Markdown内容为紧凑HTML"""
    lines = content.split('\n')
    html_lines = []
    in_code_block = False
    code_type = ''
    table_buffer = []
    in_table = False
    list_stack = []
    
    i = 0
    while i < len(lines):
        line = lines[i].rstrip()
        
        # 跳过多余的空行
        if not line.strip():
            # 只在特定情况下保留空行
            if i > 0 and i < len(lines) - 1:
                prev_line = lines[i-1].strip()
                next_line = lines[i+1].strip()
                if (prev_line.startswith('#') or next_line.startswith('#') or 
                    prev_line.startswith('```') or next_line.startswith('```')):
                    html_lines.append('')
            i += 1
            continue
        
        # 代码块处理
        if line.startswith('```'):
            if in_code_block:
                # 结束代码块
                if code_type == 'json':
                    html_lines.append('</div>')
                elif code_type == 'http':
                    html_lines.append('</div>')
                elif any(char in '\n'.join(html_lines[html_lines.index('<pre>') + 1:]) 
                        for char in ['┌', '└', '├', '│', '+-']):
                    html_lines[html_lines.index('<pre>')] = '<div class="ascii-art">'
                    html_lines.append('</div>')
                else:
                    html_lines.append('</pre>')
                in_code_block = False
                code_type = ''
            else:
                # 开始代码块
                code_lang = line[3:].strip().lower()
                if 'json' in code_lang:
                    html_lines.append('<div class="json-block">')
                    code_type = 'json'
                elif 'http' in code_lang:
                    html_lines.append('<div class="http-block">')
                    code_type = 'http'
                else:
                    html_lines.append('<pre>')
                    code_type = 'code'
                in_code_block = True
            i += 1
            continue
        
        if in_code_block:
            html_lines.append(line)
            i += 1
            continue
        
        # 表格处理
        if '|' in line and line.strip().startswith('|') and line.strip().endswith('|'):
            if not in_table:
                in_table = True
                table_buffer = []
                html_lines.append('<table>')
            
            cells = [cell.strip() for cell in line.strip('|').split('|')]
            if not all(re.match(r'^[-:]+$', cell.strip()) for cell in cells if cell.strip()):
                if len(table_buffer) == 0:
                    html_lines.append('<thead><tr>')
                    for cell in cells:
                        html_lines.append(f'<th>{cell}</th>')
                    html_lines.append('</tr></thead><tbody>')
                else:
                    html_lines.append('<tr>')
                    for cell in cells:
                        html_lines.append(f'<td>{cell}</td>')
                    html_lines.append('</tr>')
                table_buffer.append(line)
            i += 1
            continue
        else:
            if in_table:
                html_lines.append('</tbody></table>')
                in_table = False
                table_buffer = []
        
        # 标题处理
        if line.startswith('#'):
            level = 0
            for char in line:
                if char == '#':
                    level += 1
                else:
                    break
            content_text = line[level:].strip()
            html_lines.append(f'<h{level}>{content_text}</h{level}>')
        
        # 分隔线
        elif re.match(r'^-{3,}$', line.strip()):
            html_lines.append('<hr>')
        
        # 列表处理
        elif re.match(r'^\s*[-*+]\s+', line):
            content_text = re.sub(r'^\s*[-*+]\s+', '', line)
            indent_level = (len(line) - len(line.lstrip())) // 2
            
            # 管理嵌套列表
            while len(list_stack) > indent_level:
                html_lines.append('</ul>')
                list_stack.pop()
            
            if len(list_stack) <= indent_level:
                html_lines.append('<ul>')
                list_stack.append('ul')
            
            html_lines.append(f'<li>{content_text}</li>')
        
        elif re.match(r'^\s*\d+\.\s+', line):
            content_text = re.sub(r'^\s*\d+\.\s+', '', line)
            indent_level = (len(line) - len(line.lstrip())) // 2
            
            while len(list_stack) > indent_level:
                tag = list_stack.pop()
                html_lines.append(f'</{tag}>')
            
            if len(list_stack) <= indent_level:
                html_lines.append('<ol>')
                list_stack.append('ol')
            
            html_lines.append(f'<li>{content_text}</li>')
        
        else:
            # 关闭所有打开的列表
            while list_stack:
                tag = list_stack.pop()
                html_lines.append(f'</{tag}>')
            
            # 普通段落
            line = re.sub(r'`([^`]+)`', r'<code>\1</code>', line)
            line = re.sub(r'\*\*([^*]+)\*\*', r'<strong>\1</strong>', line)
            line = re.sub(r'\*([^*]+)\*', r'<em>\1</em>', line)
            html_lines.append(f'<p>{line}</p>')
        
        i += 1
    
    # 关闭未关闭的元素
    if in_table:
        html_lines.append('</tbody></table>')
    
    while list_stack:
        tag = list_stack.pop()
        html_lines.append(f'</{tag}>')
    
    return '\n'.join(html_lines)

if __name__ == "__main__":
    input_file = "cerebellar_platform_spec_ui_upgraded(1).md"
    output_file = "cerebellar_platform_spec_compact_A4.html"
    
    try:
        convert_markdown_to_compact_a4(input_file, output_file)
    except Exception as e:
        print(f"转换过程中出现错误: {e}")
        import traceback
        traceback.print_exc()
